<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Protobuf WebSocket Test</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #messages { margin-top: 10px; }
    </style>
</head>
<body>
<h1>Protobuf WebSocket Test3</h1>
<input type="text" id="messageInput" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<br />
<div id="messages"></div>

<!-- 引入 Protobuf.js 库 -->
<script src="protobuf.min.js"></script>
<script>
    // 使用XMLHttpRequest 加载 proto 文件
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'fishshoot.proto', true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 文件加载完成，解析proto文件
            const root = protobuf.parse(xhr.responseText).root
            const FishShoot = root.lookupType('fishshoot')

            // 创建 WebSocket 连接
            const socket = new WebSocket("ws://localhost:7000/ws")
            socket.binaryType = "arraybuffer"
            socket.onopen = function () {
                console.log("Connected to WebSocket server.")
            }
            socket.onmessage = function (event) {
                const uint8Array = new Uint8Array(event.data)
                const message = FishShoot.decode(uint8Array)

                console.log('Received message:', message)

                document.getElementById("messages").innerHTML = message.content
            }
            function sendMessage() {
                const message = FishShoot.create({
                    id: 1,
                    content: document.getElementById("messageInput").value
                })
                const buffer = FishShoot.encode(message).finish()
                socket.send(buffer)
                document.getElementById("messageInput").value = ""
            }
            socket.onclose = function (event) {
                console.log("WebSocket connection closed.", event)
            }
            socket.onerror = function (error) {
                console.error("WebSocket error:", error)
            }
            window.sendMessage = sendMessage
        } else if (xhr.readyState === 4) {
            console.error("Error loading proto file:", xhr.statusText)
        }
    }
    xhr.send()
</script>
</body>
</html>